import { Button, Container } from "react-bootstrap";
import useGlobalConext from "../GlobalContext";
import { Form } from "react-bootstrap";
import { useRef } from "react";
import api from "../request";
import useMessageBox from "../Modal/MessageBox_Context";
import { useRequireLogin } from "../utils";

function ProfilePage({ userId }) {
    useRequireLogin();

    const [context, dispatch] = useGlobalConext();
    const showMessageBox = useMessageBox();
    if (!userId)
        userId = context.user.id;

    const nicknameRef = useRef();
    const emailRef = useRef();
    const passwordRef = useRef();
    const phoneNumberRef = useRef();

    function handleSave() {
        api.updateProfile({
            nickname: nicknameRef.current.value,
            email: emailRef.current.value,
            phoneNumber: phoneNumberRef.current.value === '' ? null : phoneNumberRef.current.value,
        }, (err, data, res) => {
            if (err) data = res.body;
            if (data.code !== 0) {
                if (data.code === 1005)
                    showMessageBox('提示', '手机号格式不正确', 'ok');
                else
                    showMessageBox('提示', data.msg, 'ok');
                return;
            }
            showMessageBox('提示', '保存成功。', 'ok');
            dispatch({ type: 'set-user', payload: { 
                user: { ...context.user, ...data.data },
                rememberMe: true
            }});
        });
    }

    return (
        <Container>
            <h1>个人中心</h1>
            <Form className="mt-4 col-6" onSubmit={handleSave}>
                <Form.Group>
                    <Form.Label>昵称</Form.Label>
                    <Form.Control type="text" defaultValue={context.user.nickname} ref={nicknameRef} />
                </Form.Group>
                <Form.Group>
                    <Form.Label>邮箱</Form.Label>
                    <Form.Control type="email" defaultValue={context.user.email} ref={emailRef} />
                </Form.Group>
                {/* TODO 前端手机号格式验证 */}
                <Form.Group>
                    <Form.Label>手机号</Form.Label>
                    <Form.Control type="text" defaultValue={context.user.phoneNumber} ref={phoneNumberRef} />
                </Form.Group>
                {/* <Form.Group>
                    <Form.Label>密码</Form.Label>
                    <Form.Control type="password" defaultValue={context.user.password} ref={passwordRef} />
                </Form.Group> */}
                <Button variant="primary" type="submit" className="mt-2">保存</Button>
            </Form>

        </Container>
    );
}

export default ProfilePage;